from django.db.models import Q, Count
from rest_framework.decorators import action
from rest_framework.response import Response

from apps.opoc.models import Labor_service_unit
from apps.option.filters import UsersFilter
from apps.option.serializers import OptionsSerializer
from apps.pbi.models import SupplierManufactor
from extensions.permissions import *
from extensions.viewsets import *
from apps.option.serializers import *
from apps.option.permissions import *
from apps.system.models import *
from rest_framework import filters, status


# System
class RoleOptionViewSet(InfiniteOptionViewSet):
    serializer_class = RoleOptionSerializer
    permission_classes = [IsAuthenticated, RoleOptionPermission]
    search_fields = ['name']
    queryset = Role.objects.all()


class UserOptionViewSet(InfiniteOptionViewSet):
    queryset = User.objects.all()
    serializer_class = UserOptionSerializer
    permission_classes = [IsAuthenticated, UserOptionPermission]
    filter_backends = (DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter)
    filter_class = UsersFilter
    # filterset_fields = ['is_active','company']
    search_fields = ['username', 'name','roles__permissions__code']

    def get_queryset(self):
        # queryset = super().get_queryset().filter(team=self.team)
        permission = self.request.query_params.get('permission', None)
        print(permission)
        query=Q()
        if permission:
            query = query & Q(permissions__contains=[permission])
        queryset = User.objects.filter(query)
        return queryset

    @action(detail=False, methods=['get'])
    def get_username(self, request, *args, **kwargs):
        username=self.request.query_params.get('username', None)
        query = Q()
        if username:
            query = query & Q(username__contains=username)
            result = User.objects.filter(query).aggregate(username_count=Count('username'))

            if(result["username_count"]>0):
                username_repeat=True
                suffix = result["username_count"]
                while username_repeat:
                    suffix  += 1
                    new_username=username+str(suffix)
                    res = User.objects.filter(Q(username__contains=new_username)).aggregate(username_count=Count('username'))
                    if res["username_count"]==0:
                        username_repeat=False
                        return Response(data={"username":new_username}, status=status.HTTP_200_OK)
        return Response(data={"username": username}, status=status.HTTP_200_OK)


class Labor_service_unitOptionsViewSet(InfiniteOptionViewSet):
    class Labor_service_unitOptionsSerializer(OptionsSerializer):
        class Meta:
            model = Labor_service_unit
            fields = ['id', 'name']

    serializer_class = Labor_service_unitOptionsSerializer
    permission_classes = [IsAuthenticated]
    filterset_fields = ['company']
    search_fields = ['name']
    ordering_fields = ['id']
    queryset = Labor_service_unit.objects.all()


class SupplierManufactorsOptionsViewSet(InfiniteOptionViewSet):
    class SupplierManufactorSerializer(OptionsSerializer):
        class Meta:
            model = SupplierManufactor
            fields = ['id', 'name']

    serializer_class = SupplierManufactorSerializer
    permission_classes = [IsAuthenticated]
    filterset_fields = ['company']
    search_fields = ['name']
    ordering_fields = ['id']
    queryset = SupplierManufactor.objects.all()


__all__ = [
    'RoleOptionViewSet', 'UserOptionViewSet',
]
